<template>
	<div class="symptoms" :style="{'height':relHeight}">
		<!--搜索框-->
		<div class="search-div clearfix">
            <p class="input-wrap left" :style="{'width':reduceInputWidth}">
            		<img src="../assets/img/search.svg" alt="img"  class="search-icon"/>
            		<input type="text" placeholder="搜索..."  @input="searchChange" @focus="showMaskWhiteFn"
            			v-model="seachInputVal" @keyup.13="showHistoryList"/>
            		<img src="../assets/img/search-icon-delete.svg" alt="img"  class="search-icon-delete" v-show="showCancelBtn" @click="clearInputVal"/>
            </p>
            <p class="right" style="width:10%;margin-top:.2rem;" @click="cancelSearchPage()" v-show="showCancelBtn">取消</p>
       </div>
       <!--左右排列的列表-->
       <div class="symptom-wrap">
            <div class="content-sym clearfix">
           		<!--左侧-->
                <div class="left-tab left">
	                	<!--<scroller lock-x  :style="{'height':reduceHeight}" @on-scroll="onScrollLeft" ref="scrollerEvent">-->
	                    <div class="sort-list" style="overflow:auto;height:16rem;" :style="{'padding-bottom':reduceHeight}">
	                    		<div class="sort-item" v-for="(item,index) in sortVal" @click="clickSortList(index)" :class="[kouweiSpan==index?'sortItemActive':'']">
	                    			<img :src="kouweiSpan==index?'../../static/img/symptoma'+index+'.png':'../../static/img/symptom'+index+'.png'">
	                    			<p>{{item.name}}</p>
	                    		</div>
	                    </div>
	                 <!--</scroller>-->
                </div>
                <!--右侧-->
				<div class="right-tab left">
					<!--<scroller lock-x  :style="{'height':reduceHeight}" @on-scroll="onScrollRight" ref="scrollerEvent">-->
						<div style="overflow:auto;height:16rem;" :style="{'padding-bottom':reduceHeight}">
							<div v-for="(itemList,index) in listVal" v-if="itemList.isCommonZ">
								<p style="color:#999;font-size:.33rem;margin-bottom:.3rem;">——  {{itemList.name}}  ——</p>
								<div class="clearfix sym-each-line">
									<div v-for="(itemListSon,indexSon) in itemList.sonList" class="left sym-text">
										<span @click="setListCheck(1,indexSon,itemListSon.name,itemListSon.id,itemListSon.category,index)"
										:class="[itemListSon.checked?'symActive':'']">{{itemListSon.name}}
									</span>
									</div>
								</div>
							</div>
							<div class="clearfix sym-each-line">
								<div v-for="(item,index) in listVal" class="left sym-text " :data-index="index"
								style="position:relative;" v-if="!item.isCommonZ">
									<span @click="setListCheck(0,index,item.name,item.id,item.category)"
										:class="[item.checked?'symActive':'']">{{item.name}}
										<img src="../assets/img/question_mask.svg" class="punctuation_mark" @click.stop="showExplainFn(item.notification.text,item.name)"
										v-if="item.notification && item.notification.level=='LevelInfo'">
										<img src="../assets/img/exclamation.svg" class="punctuation_mark" @click.stop="showExplainFn(item.notification.text,item.name)"
										v-if="item.notification && item.notification.level=='LevelWarn'">
									</span>
								</div>
							</div>
						</div>

					<!--</scroller>-->
				</div>
            </div>
        </div>
        <!--footer-->
        <div class="buy-car-div animated fadeInUp" v-show="showChooseNumber">
        		<!--已选症状列表-->
	        	<div class="choose-symptom-list" v-show="showChooseSymptom">
	            <div class="choice-item clearfix" v-for="(item,index) in arr">
	                <strong class='left'>{{item.text}}</strong>
	                <!--<span class="left arr-category">{{item.category}}</span>-->
	                <img src="../assets/img/removeItem.svg" class="right" @click="removeSymptomItem(item.id)"
	                :data-index="index" style="width:.5rem;height:.5rem;margin-top:.25rem;">
	            </div>
	        </div>
	        <div class="clearfix">
	        		<div class="left buy-car-left" @click="showChooseSymptomFn">
	        			<p class="car-icon">
	        				<img src="../assets/img/logo.png" alt="robot" class="car-img"/>
	        			</p>
	        			<p style="margin-top:-.2rem;">已选<span>{{arr.length}}</span>个症状</p>
	        			<p style="color:rgba(255,255,255,.4);font-size:.32rem;margin-top:-.77rem;margin-left:.5rem;">点击可修改已选症状</p>
	        		</div>
        			<div class="left buy-car-right" @click="completeSymptom">完成</div>
	        </div>
       </div>
       <!--遮罩层 白色和黑色-->
       	<div id="mask"  v-show="showMask" @click="hideBuyCar"></div>
		<div id="mask-white" v-show="showMaskWhite"></div>
		<!--解释文案-->
		<div class="explain-wrap" v-show="showExplain">
			<p class="explain-title text-center">{{explainName}}</p>
			<p class="explain-text text-left">
				{{explainText}}
			</p>
			<p class="text-center explain-title" @click="hideExplain" style="color:#1CB9B5;">知道了</p>
		</div>
		<!--搜索开始 包括搜索历史 常见症状-->
		<div class="search-page" v-show="showshow">
			<div v-show="showSearchPage">
				<!--搜索历史-->
				<div class="search-history" v-show="showSearchRecord">
					<p class="clearfix">
						<span class="left search-title">搜索历史</span>
						<span class="right search-title-spe" @click="clearCacheHistory">清除历史</span>
					</p>
					<div class="search-all-list clearfix">
						<p class="search-all-item left" v-for="(item,index) in historyArr" @click="clickSearckList(item.id,item.name,item.category)">
							{{item.name}}
						</p>
					</div>
				</div>
				<!--常见症状-->
				<div class="search-high">
					<p class="text-left search-title">常见症状</p>
					<div class="search-all-list clearfix">
						<p class="search-all-item left" v-for="(item,index) in commonSymptom" @click="clickSearckList(item.id,item.name,item.category)">
							{{item.name}}
						</p>
					</div>
				</div>
			</div>
			<!--搜索列表-->
			<div v-show="showSearchResult" >
				<div class="clearfix search-con-ist" v-for="(item,index) in searchList" @click="clickSearckList(item.id,item.name,item.category)">
					<p class="left search-con-left" >{{item.name}}</p>
					<p class="right search-con-right">{{item.category}}</p>
				</div>
			</div>
		</div>
		<!--搜索结束-->
	</div>
</template>

<script>
	import { Scroller} from 'vux'
	import { buildSymptom } from '../assets/js/common.js';
	import {mapState} from 'vuex'

	import {urlSymptomList,urlSymptomSuggest} from '../api/api'
	export default {
        name: 'Search',
        data(){
            return{
            		relHeight:'',
            		reduceHeight:'1rem',
            		seachInputVal:'',  //输入框的value
            		reduceInputWidth:'100%',
            		showshow:false, //测试
            		showMask:false,
            		showMaskWhite:false,
            		showSearchRecord:false,
            		showChooseSymptom:false,
            		showChooseNumber:false,
            		showExplain:false,
            		showSearchPage:false,
            		showSearchResult:false, //显示搜索结果列表
            		showCancelBtn:false,// 取消按钮
            		explainText:'',//解释文案
            		explainName:'',
            		//右侧的每个症状列表
            		symptomEachList:[],
            		arr:[],
            		historyArr:[],
            		rangeValue:'',
            		sortVal:[],
            		listVal:[],
            		//搜索
            		searchList:[],
            		commonSymptom:[],//常见症状
            		kouweiSpan:0,
            }
        },
        components: {
		    Scroller
		},
        computed: {
          ...mapState(['inquiryDataList','fromRecordsPageFlag'])
        },
        mounted(){
			//判断搜索历史是否为空
//			if(localStorage.getItem("history")){
//				this.showSearchRecord=true;
//				this.historyArr=JSON.parse(localStorage.getItem("history"));
//			}
			//执行症状列表请求
			this.urlSymptomListFn()
	    	},
	    	created(){
	    		this.$nextTick(() => {
				this.relHeight=document.documentElement.clientHeight+'px'
          	})
	    	},
        methods:{
        		//症状列表请求
       		urlSymptomListFn(){
       			let sendData={
       				gender:this.$route.params.gender,
       				age:this.$route.params.age,
       				start:0,
       				count:2000
       			},
       			loadCommonSymptom=true;
              urlSymptomList(sendData).then(response => {
                this.symptomEachList=response.data;
                this.initBuildSymptom(0, loadCommonSymptom);
              }).catch(error => {
	         	    console.log(34)
	        		});
	        		let sendDataSort={
       				gender:this.$route.params.gender,
       				age:this.$route.params.age,
       				sort:'hot',
       				start:0,
       				count:12
       			};
              urlSymptomList(sendDataSort).then(response => {
                this.commonSymptom=response.data.items;
              }).catch(error => {
	         	    console.log(34)
	        		});
       		},
        		onScrollLeft (pos) {
		      	this.scrollTop = pos.top
		    },
		    onScrollRight(pos){
		    		this.scrollTop = pos.top
		    },
		    //打开解释文件
		    showExplainFn(text,name){
		    		this.explainName=name;
		    		this.explainText=text;
		    		this.showMask=true;
            		this.showExplain=true;
		    },
            //关闭解释文件
            hideExplain(){
            		this.showMask=false;
            		this.showExplain=false;
            },
            hideBuyCar(){
            		this.showMask=false;
            		this.showChooseSymptom=false;
            },
            //删除数组中确定项
            removeByValue(arr, idVal) {
			  for(var i=0; i<arr.length; i++) {
			    if(arr[i]['id'] == idVal) {
			      arr.splice(i, 1);
			      break;
			    }
			  }
			},
			initBuildSymptom(idx, loadCommonSymptom,arrSelect){
				idx = idx ? idx : 0;
				//执行组装症状结构
				let {_list, _sort,_listSpe} = buildSymptom(this.symptomEachList, loadCommonSymptom,arrSelect);
				if(_sort == []){
					return false;
				}
				_list = JSON.parse(JSON.stringify(_list));
				this.sortVal=_sort;
				this.listVal=_list[idx];
			},
			// 选择分类
		    clickSortList(idx, loadCommonSymptom) {
		    		let arrSelect=JSON.parse(JSON.stringify(this.arr));
		    		this.kouweiSpan = idx;
		    		this.initBuildSymptom(idx, loadCommonSymptom,arrSelect);
		    		for (let i = 0; i < this.arr.length; i++) {
		            for (let j = 0; j < this.listVal.length; j++) {
		                if (this.arr[i]['id'] == this.listVal[j]['id']) {
		                    this.listVal[j].checked = true;
		                }
		            }
		       }
		    },
          //症状选中和反选症状
          setListCheck(mark,idx,name,id,category,index){
				    //判断是否选中或者反选
          		 if(mark===1){
          		 let checked2 = this.listVal[index].sonList[idx].checked;
          			if(this.listVal[index].sonList[idx].checked === false ){
	          			this.listVal[index].sonList[idx].checked = true;
	          			this.arr.push({
				          id:id,
				          text:name,
				          category:category
				        })
	          			this.showChooseNumber=true;
	          			this.reduceHeight='2rem';
	          		}else{
	          			this.listVal[index].sonList[idx].checked = false;
                  this.removeByValue(this.arr,id);
                  this.reduceHeight='2rem';
                  if(this.arr.length<=0){
                    this.showChooseNumber=false;
                    this.reduceHeight='2rem';
                   }
	          		}
          		 }else if(mark===0){
          		 	let checked = this.listVal[idx].checked;
          		 	if(this.listVal[idx].checked === false ){
	          			this.listVal[idx].checked = true;
	          			this.arr.push({
				          id:id,
				          text:name,
				          category:category
				        })
	          			this.showChooseNumber=true;
	          			this.reduceHeight='2rem';
	          		}else{
	          			this.listVal[idx].checked = false;
                  this.removeByValue(this.arr,id);
                  this.reduceHeight='2rem';
                  if(this.arr.length<=0){
                    this.showChooseNumber=false;
                    this.reduceHeight='1rem';
                   }
	          		}
          		 }

            },
            showChooseSymptomFn(){
            		if(this.arr.length>0){
            			this.showMask = !this.showMask;
            			this.showChooseSymptom =! this.showChooseSymptom;
            		}
            },
            removeSymptomItem(idx_remove){
            		console.log(idx_remove,'idx_remove')
            		console.log(this.listVal,'this.listVal')
            		for (let i = 0; i < this.listVal.length; i++) {
            			if (this.listVal[i]['id'] == idx_remove) {
			            this.listVal[i].checked = false;
			            break;
            			}else if(this.listVal[i].isCommonZ){//兼容删除常见症状中的
            				let _this = this;
            				this.listVal[i].sonList.map(function(coVal, coIdx){
            					if (_this.listVal[i].sonList[coIdx]['id'] == idx_remove) {
            						_this.listVal[i].sonList[coIdx].checked = false;
            					}
            				});
            			}
		        }
            		this.removeByValue(this.arr,idx_remove);
            		if(this.arr.length==0){
            			this.showMask=false;
            			this.showChooseSymptom=false;
            			this.showChooseNumber=false;
            			this.reduceHeight='2rem';
            		}
            },
            //聚焦事件出现搜索内容
            showMaskWhiteFn(){
            		this.showshow=true;
            		this.showMaskWhite=true;
            		this.showCancelBtn=true;
            		this.showChooseNumber=false;
            		this.reduceInputWidth='88%'
            		this.showSearchPage=true;
            },
            //input 输入事件
            searchChange(){
                if (!this.seachInputVal=='') {
             		this.showSearchPage=false;
                		this.showSearchResult=true;
                }else{
                		this.showSearchPage=true;
                		this.showSearchResult=false;
                }
                let sendData={
       				gender:this.$route.params.gender,
       				age:this.$route.params.age,
       				text:this.seachInputVal
       			},
       			_this=this;
				urlSymptomSuggest(sendData).then(response => {
					this.searchList=response.data.items;
				}).catch(error => {
	         	    console.log(34)
	        		});
            },
            clearInputVal(){
            		this.seachInputVal='';
            		this.showshow=true;
            		this.showSearchPage=false;
            		this.showSearchResult=false;
            },
            clickSearchFn(){
            		if(this.arr.length>0){
            			this.showChooseNumber=true;
            		}
		        this.seachInputVal='';
		        this.showshow=false;
		        this.showMaskWhite=false;
            },
            //点击搜索列表的item
             clickSearckList(id,name,category) {
             	this.showSearchPage=true;
                this.showSearchResult=false;
              	this.showCancelBtn=false;
				this.reduceInputWidth='100%';
		        let json = {
		            id: id,
			        text:name,
			        category:category,
		            checked: true
		        };
		        for (let i = 0; i < this.arr.length; i++) {
		            if (this.arr[i].id == id) {
		            		this.clickSearchFn()
		              	return;
		            }
		        }

		        for (let i = 0; i < this.listVal.length; i++) {
		            if (this.listVal[i].id == id) {
		               this.listVal[i].checked=true
		            }
		        }
		        this.arr.push(json);
		        this.clickSearchFn();
		        this.showHistoryList(id,category);
		        console.log(this.arr,'arrarr')
		    },
            cancelSearchPage(){
            	//点击取消清空内容并返回症状列表
            		this.seachInputVal='';
            		this.showMaskWhite=false;
            		this.showshow=false;
            		this.showCancelBtn=false;
            		if(this.arr.length>0){
            			this.showChooseNumber=true;
            		}
            		this.reduceInputWidth='100%';
            		this.showSearchPage=false;
            },
            //数组去重
            removeByValue(arr, idVal) {
              for(var i=0; i<arr.length; i++) {
                if(arr[i]['text'] == idVal) {
                  arr.splice(i, 1);
                  break;
                }
              }
            },
            showHistoryList(val,category){
            		//如果输入完毕则搜索历史增加一条
            		this.showSearchPage=true;
                	this.showSearchResult=false;
                	this.showSearchRecord=true;
                	let _isPushHisArr=true,
	                	_this=this;
                	//判断当前元素不存在historyArr才追加
                	this.historyArr.map(function(hisItem,hisIdx){
            			if(hisItem.id==val || hisItem.id==_this.seachInputVal){
            				_isPushHisArr = false;
            			}
            		});
                	if(true === _isPushHisArr){
                		this.historyArr.unshift({
			          id: this.seachInputVal || val,
			          name: this.seachInputVal || val,
			          category:category
			        });
                	}
            		//如果大于6个则展示后面输入的6个
		        if (this.historyArr.length > 6){
		          this.historyArr=this.historyArr.slice(0, 6);
		        }
            		localStorage.setItem("history",JSON.stringify(this.historyArr))
            },
            clearCacheHistory(){
            		this.historyArr=[];
            		this.showSearchRecord=false;
            		localStorage.removeItem("history");
            },
            //点击完成
            completeSymptom(){
	            	let symptoms = [],
            			str='',
            			self=this,
            			inquiryDataList=this.inquiryDataList,
            			len = inquiryDataList.length;
            		self.arr.map(function (val, idx) {
		            symptoms.push(val.id);
		            str+=val.text;
		            if(idx<self.arr.length-1){
		                str+=', '
		            }
		        })
            		inquiryDataList[len-1].answer.push({
		            type:'text',
		            value:str
		        });
            		this.$store.dispatch('selectedSymptomFn',symptoms);
            		this.$store.dispatch('inquiryDataListFn',inquiryDataList);
            		this.$store.dispatch('fromRecordsPageFlagFn',false)
            		this.$router.push({name: 'inquiry'});
            }
        },

    }
</script>

<style>
	@import url("../assets/css/symptoms.css");
</style>
